package com.caizi.socket.normal;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.nio.channels.SocketChannel;

public class Handler implements Runnable {
    SocketChannel socketChannel;

    public Handler(SocketChannel socketChannel) {
        this.socketChannel = socketChannel;
    }

    @Override
    public void run() {
        handler();
    }

    private void handler() {
        Socket socket = null;
        try {
            socket = socketChannel.socket();
            System.out.println("接收到客户连接，来自：" + socket.getInetAddress() + ":" + socket.getPort());

            BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            PrintWriter pw = new PrintWriter(socket.getOutputStream(), true);

            String msg = null;

            while ((msg = br.readLine()) != null) {
                System.out.println(msg);
                pw.println(msg);
                if ("bye".equals(msg)) {
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    public String echo(String msg) {
        return "echo:" + msg;
    }
}
